<template>
    <div>
         <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
           
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert show-icon title="注意：只允许第三级分类设置参数!" type="warning" :closable="false"></el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="cat-top">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 级联选择 -->
                     <el-cascader clearable
                        v-model="cateValueArr"
                        :options="catelist"
                        :props="cateProps"
                        expand-trigger="hover"
                        @change="cateHandleChange"></el-cascader>
                </el-col>
            </el-row>

            <!-- tab标签页 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick" >
                <!-- 添加动态参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button :disabled="isBtnDisabled" type="primary" size="mini"
                    @click="addDialogVisible = true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe max-height="400">
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                
                                <el-tag :closable="true" v-for="(item ,i) in scope.row.attr_vals" :key="i"
                                @close="handleClose(i, scope.row)">{{item}}</el-tag>
                                <!-- 输入文本框 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit"
                                @click="showEditDialog(scope.row.attr_id)"> 修改</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete"
                                @click="deletedParamsDialog(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane  label="静态属性" name="only">
                    <el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="addDialogVisible = true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe max-height="400">
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            
                             <template slot-scope="scope">
                                <el-tag :closable="true" v-for="(item ,i) in scope.row.attr_vals" :key="i"
                                @close="handleClose(i, scope.row)">{{item}}</el-tag>
                                <!-- 输入文本框 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>

                        </el-table-column>
                        <!-- 索引 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit"
                                @click="showEditDialog(scope.row.attr_id)"> 修改</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete"
                                @click="deletedParamsDialog(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
            </el-tabs>
        
        </el-card>

        <!-- 添加参数的对话框 -->
        <el-dialog @close="addDialogClose"
            :title="'添加' + titleText"
            :visible.sync="addDialogVisible"
            width="50%">

            <el-form ref="formRef" :model="addForm" :rules="addFormRules" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改参数的对话框 -->
        <el-dialog @close="editDialogClose"
            :title="'修改' + titleText"
            :visible.sync="editDialogVisible"
            width="50%">

            <el-form ref="editformRef" :model="editForm" :rules="editFormRules" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script lang="ts">

export default {
    data(){
        return {
            // 控制tab文本输入框
            // inputVisible:false,
            // inputValue:'',
            // 被激活的页签的名称
            activeName:'many',
            manyTableData:[],
            onlyTableData:[],
            // 所有商品分类
            catelist:[],
            // 级联选择的值
            cateValueArr:[],
            // 级联选择器的配置
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // 添加属性对话框
            addDialogVisible:false,
            editDialogVisible:false,
            // 添加属性，表单数据
            addForm:{
                attr_name:''
            },
            editForm:{
                attr_name:''
            },
            // 表单验证规则
            addFormRules:{
                attr_name:[
                    {required:true , message:'请输入参数名称' , trigger:'blur'}
                ]
            },
            // 表单验证规则
            editFormRules:{
                attr_name:[
                    {required:true , message:'请输入参数名称' , trigger:'blur'}
                ]
            }

        }
    },
    created(){
        this.getCateList()
    },
    methods:{
        async getCateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status !== 200) {
                return this.$message.error('获取商品分类失败！')
            }

            this.catelist = res.data
            // console.log(this.catelist);
            
        },
        // 级联选择器选择值变化，触发
        cateHandleChange(){
            
            this.getParamsData()
        },
        // tab页签点击事件
        handleTabClick(){
            // console.log(this.activeName);
           this.getParamsData()
            
        },
        // 获取参数列表数据
        async getParamsData(){
            // 选中三级分了
            if(this.cateValueArr.length !==3){
                this.cateValueArr = []
                this.manyTableData = [],
                this.onlyTableData = []
                return
            }

            // 证明是三级分类
            // console.log(this.cateValueArr);
             // 根据所选的分类id，发起请求
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                params: {sel:this.activeName}
            })
            if(res.meta.status !== 200){
                return this.$message.error('获取参数列表失败!')
            }

            // console.log(res.data);

            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ?
                item.attr_vals = item.attr_vals.split(',') : []

                // 控制文本框的显示与隐藏
                item.inputVisible = false
                // 文本框中输入的值
                item.inputValue = ''
                
            });

            console.log(res.data);
            

            if(this.activeName === 'many'){
                this.manyTableData = res.data
            } else {
                this.onlyTableData = res.data
            }
            
        },
        // 监听添加对话框的关闭事件
        addDialogClose(){
            this.$refs.formRef.resetFields()
        },
        // 点击确定按钮，发起请求  添加属性
        addParams(){
            // console.log(this.addForm.attr_name);
            
            this.$refs.formRef.validate(async valid =>{
                if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                })

                if(res.meta.status !== 201){
                    return this.$message.error('添加参数失败！')
                }

                this.$message.success('添加参数成功！')
                this.addDialogVisible = false
                this.getParamsData()
            })
        },
        // 点击修改按钮
        async showEditDialog(attr_id){
            const {data:res} = await this.$http(`categories/${this.cateId}/attributes/${attr_id}`,{
                params:{ attr_id: this.activeName}
            })

            if(res.meta.status !== 200){
                return this.$message.error('获取修改参数失败！')
            }

            this.editForm = res.data
            // console.log(res.data);
            

            this.editDialogVisible = true

        },
        // 监听关闭修改参数对话框 重置修改表单
        editDialogClose(){

            this.$refs.editformRef.resetFields()
        },
        // 修改参数，点击确定事件
        editParams(){
            this.$refs.editformRef.validate(async valid =>{
                if(!valid) return

                const { data :res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                {
                    attr_name: this.editForm.attr_name,
                    attr_sel: this.activeName
                })

                if(res.meta.status !== 200){
                    return this.$message.error('修改失败！')
                }

                this.$message.success('修改成功!')
                this.editDialogVisible = false
                this.getParamsData()
            })


            
        },
        // 根据id删除 对应参数
        async deletedParamsDialog(attr_id){
           const resultRes =await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((resultResCan) => resultResCan)
        .catch((err) => err);

        if(resultRes === 'cancel'){
            return this.$message({
            type: 'info',
            message: '已取消删除'
          }); 
        }

        const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)

        if(res.meta.status !== 200){
            return this.$message.erroe('删除属性失败!')
        }

        
        this.$message({
            type: 'success',
            message: '删除成功!'
          });
        this.editDialogVisible = false
        this.getParamsData()
        },
        // 文本框失去焦点，或者摁下enter都会触发
        async handleInputConfirm(row){
            // console.log('ok');
            // 1 判断是否是有效内容
            if(row.inputValue.trim().length === 0){
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            
            // 2 输入了有效内容，继续执行操作  push到数组，触发渲染
            row.attr_vals.push(row.inputValue.trim())

            row.inputValue = ''
            row.inputVisible = false

            // 3 发起请求，发送到后端保存
            this.saveAttrVals(row)

            

            
        },
        // 发起请求把对tag的删除 增加操作保存到数据库
        async saveAttrVals(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(',')
            })

            if(res.meta.status !== 200){
                return this.$message.error('添加失败！')
            }
        },
        // tag和文本输入框切换
        showInput(row){
            row.inputVisible = true
            // 此时虽然重置为true，但是还是button按钮，还没有重新渲染成input

            // 让文本框自动获得焦点
            // $nextTick 方法的作用 ， 就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
            this.$nextTick(_ => { //核心
                 this.$refs.saveTagInput.$refs.input.focus();
             });
        },
        // 删除对应参数的tag
        handleClose(i, row){
            row.attr_vals.splice(i, 1)
            this.saveAttrVals(row)
        }
    },
    computed:{
        // 按钮的是否禁用
        isBtnDisabled(){
            if(this.cateValueArr.length !== 3){
                return true
            }

            return false
        },
        // 当前选中的三级分类ID
        cateId(){
            if(this.cateValueArr.length === 3){
                return this.cateValueArr[2]
            }

            return null
        },
        // 动态计算显示标题
        titleText(){
            if(this.activeName === 'many'){
                return '动态参数'
            }

            return '静态参数'
        }
    }
}
</script>

<style lang="less" scoped>
.cat-top{
    margin: 15px 0;
}
.el-cascader{
    width: 25%;
}
.el-tag{
    margin: 15px;
}
.input-new-tag{
    width: 120px;
}
</style>
